<template>
  <div class="order-pay">
    <el-card class="pay-card">
      <template #header>
        <div class="card-header">
          <span>订单支付</span>
        </div>
      </template>

      <!-- 订单信息 -->
      <div class="order-info">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ orderInfo.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">支付金额：</span>
          <span class="value price">¥{{ orderInfo.totalAmount }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单时间：</span>
          <span class="value">{{ orderInfo.createTime }}</span>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="products-list">
        <div v-for="product in orderInfo.products" :key="product.productId" class="product-item">
          <el-image :src="product.image" :preview-src-list="[product.image]" class="product-image" />
          <div class="product-info">
            <h4>{{ product.productName }}</h4>
            <p class="price">¥{{ product.price }}</p>
            <p class="quantity">x{{ product.quantity }}</p>
          </div>
          <div class="product-total">
            <p class="subtotal">小计：¥{{ (product.price * product.quantity).toFixed(2) }}</p>
          </div>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <el-radio-group v-model="selectedPayment" class="method-list">
          <el-radio-button label="1">
            <el-icon><AlipayCircleFilled /></el-icon>
            支付宝支付
          </el-radio-button>
          <el-radio-button label="2">
            <el-icon><WechatFilled /></el-icon>
            微信支付
          </el-radio-button>
          <el-radio-button label="3">
            <el-icon><CreditCard /></el-icon>
            银行卡支付
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 支付按钮 -->
      <div class="pay-actions">
        <div class="pay-info">
          <span>应付金额：</span>
          <span class="total-price">¥{{ orderInfo.totalAmount }}</span>
        </div>
        <div class="action-buttons">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" :loading="paying" @click="handlePay">
            立即支付
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 支付二维码弹窗 -->
    <el-dialog
      v-model="qrCodeVisible"
      title="扫码支付"
      width="400px"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="qr-code-content">
        <div class="qr-code-wrapper">
          <img :src="qrCodeUrl" alt="支付二维码" class="qr-code-image" />
        </div>
        <p class="qr-code-tip">
          请使用{{ getPaymentName(selectedPayment) }}扫描二维码完成支付
        </p>
        <div class="qr-code-amount">
          <span>支付金额：</span>
          <span class="price">¥{{ orderInfo.totalAmount }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPay">取消支付</el-button>
          <el-button type="primary" @click="checkPayStatus">
            已完成支付
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { AlipayCircleFilled, WechatFilled, CreditCard } from '@element-plus/icons-vue'
import { getOrder, payOrder, checkOrderStatus } from '@/api/user/order'

const route = useRoute()
const router = useRouter()
const orderInfo = ref({})
const selectedPayment = ref('1')
const paying = ref(false)
const qrCodeVisible = ref(false)
const qrCodeUrl = ref('')

// 获取订单信息
const getOrderInfo = async () => {
  try {
    const res = await getOrder(route.params.orderId)
    if (res.code === 200) {
      orderInfo.value = res.data
      // 如果订单已支付，跳转到订单详情页
      if (orderInfo.value.status !== '0') {
        ElMessage.warning('订单已支付')
        router.replace(`/user/orders/${orderInfo.value.orderId}`)
      }
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    ElMessage.error('获取订单信息失败')
  }
}

// 获取支付方式名称
const getPaymentName = (method) => {
  const methodMap = {
    '1': '支付宝',
    '2': '微信',
    '3': '银行卡'
  }
  return methodMap[method]
}

// 处理支付
const handlePay = async () => {
  if (!selectedPayment.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  paying.value = true
  try {
    const res = await payOrder(orderInfo.value.orderId, selectedPayment.value)
    if (res.code === 200) {
      qrCodeUrl.value = res.data
      qrCodeVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取支付二维码失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  } finally {
    paying.value = false
  }
}

// 检查支付状态
const checkPayStatus = async () => {
  try {
    const res = await checkOrderStatus(orderInfo.value.orderId)
    if (res.code === 200) {
      if (res.data.status === '1') {
        ElMessage.success('支付成功')
        qrCodeVisible.value = false
        router.push(`/user/orders/${orderInfo.value.orderId}`)
      } else {
        ElMessage.warning('未检测到支付完成，请确认支付状态')
      }
    }
  } catch (error) {
    console.error('检查支付状态失败:', error)
    ElMessage.error('检查支付状态失败')
  }
}

// 取消支付
const cancelPay = () => {
  qrCodeVisible.value = false
}

// 取消订单
const cancel = () => {
  router.push(`/user/orders/${orderInfo.value.orderId}`)
}

onMounted(() => {
  getOrderInfo()
})
</script>

<style lang="scss" scoped>
.order-pay {
  padding: 20px;

  .pay-card {
    .card-header {
      font-weight: bold;
    }

    .order-info {
      padding: 20px;
      background-color: #f8f8f8;
      border-radius: 4px;
      margin-bottom: 20px;

      .info-item {
        display: flex;
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 100px;
          color: #666;
        }

        .value {
          flex: 1;
          
          &.price {
            color: #f56c6c;
            font-size: 18px;
            font-weight: bold;
          }
        }
      }
    }

    .products-list {
      margin-bottom: 30px;

      .product-item {
        display: flex;
        align-items: center;
        padding: 20px;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .product-image {
          width: 80px;
          height: 80px;
          object-fit: cover;
          margin-right: 20px;
        }

        .product-info {
          flex: 1;

          h4 {
            margin: 0 0 10px;
            font-size: 16px;
          }

          .price {
            color: #f56c6c;
            font-weight: bold;
            margin: 5px 0;
          }

          .quantity {
            color: #666;
          }
        }

        .product-total {
          .subtotal {
            font-weight: bold;
            color: #f56c6c;
          }
        }
      }
    }

    .payment-methods {
      margin-bottom: 30px;

      h3 {
        margin: 0 0 20px;
        font-size: 16px;
      }

      .method-list {
        display: flex;
        gap: 20px;

        :deep(.el-radio-button__inner) {
          display: flex;
          align-items: center;
          gap: 5px;
          padding: 12px 20px;
        }
      }
    }

    .pay-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      background-color: #f8f8f8;
      border-radius: 4px;

      .pay-info {
        font-size: 16px;

        .total-price {
          color: #f56c6c;
          font-size: 24px;
          font-weight: bold;
        }
      }

      .action-buttons {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

.qr-code-content {
  text-align: center;

  .qr-code-wrapper {
    margin: 20px 0;

    .qr-code-image {
      width: 200px;
      height: 200px;
    }
  }

  .qr-code-tip {
    color: #666;
    margin: 15px 0;
  }

  .qr-code-amount {
    font-size: 16px;
    margin-top: 15px;

    .price {
      color: #f56c6c;
      font-size: 20px;
      font-weight: bold;
    }
  }
}
</style> 